import { pinia } from "@/pinia"
import { DeviceEnum, SIDEBAR_CLOSED, SIDEBAR_OPENED } from "@@/constants/app-key"
import { getSidebarStatus, setSidebarStatus } from "@@/utils/cache/local-storage"
import { defineStore } from "pinia"
import { ref, computed } from "vue"

interface Sidebar {
  opened: boolean
  withoutAnimation: boolean
}

/** 设置侧边栏状态本地缓存 */
function handleSidebarStatus(opened: boolean) {
  opened ? setSidebarStatus(SIDEBAR_OPENED) : setSidebarStatus(SIDEBAR_CLOSED)
}

/**
 * appState
 */
export interface AppState {
  // 加载中
  spinning: boolean;
  spinningText: {
    change: boolean;
    text: string;
  };
}

export const appState = defineStore("app-store", () => {
  const spinning = ref(true);
  const spinningText = ref({
    change: false,
    text: "",
  });

  const getSpinning = computed(() => spinning.value);

  function setSpinning(param: boolean) {
    spinning.value = param;
  }

  return {
    spinning,
    spinningText,
    getSpinning,
    setSpinning
  };
});

// 保留原有的 useAppStore 以向后兼容
export const useAppStore = defineStore("app", () => {
  // 侧边栏状态
  const sidebar = ref<Sidebar>({
    opened: getSidebarStatus() !== SIDEBAR_CLOSED,
    withoutAnimation: false,
  });

  // 设备类型
  const device = ref(DeviceEnum.Desktop as unknown as string);
  // 尺寸
  const size = ref("medium");

  function toggleSidebar() {
    sidebar.value.opened = !sidebar.value.opened;
    sidebar.value.withoutAnimation = false;
    handleSidebarStatus(sidebar.value.opened);
  }

  function closeSidebar(withoutAnimation: boolean) {
    sidebar.value.opened = false;
    sidebar.value.withoutAnimation = withoutAnimation;
    handleSidebarStatus(false);
  }

  function toggleDevice(newDevice: string) {
    device.value = newDevice;
  }

  function setSize(newSize: string) {
    size.value = newSize;
  }

  return {
    sidebar,
    device,
    size,
    toggleSidebar,
    closeSidebar,
    toggleDevice,
    setSize
  };
});

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function useAppStoreOutside() {
  return useAppStore(pinia)
}
